package com.suning.sawp.service.impl.dao;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import com.suning.sawp.intf.dao.StoreManLoginLogDaoService;
import com.suning.sawp.po.StoreManLoginLog;

@Service("storeManLoginLogDaoService")
public class StoreManLoginLogDaoServiceImpl implements StoreManLoginLogDaoService {

    @Resource
    MongoOperations mongoTemplate;
    
    @Override
    public void addLoginLog(StoreManLoginLog loginLog) {
        mongoTemplate.insert(loginLog);
    }

    @Override
    public void deleteLoginLogBeforeDate(String staffId, Date date) {
        Query query = new Query();
        Criteria criteria = new Criteria();
        criteria.and(StoreManLoginLog.Attributes.STAFF_ID).is(staffId)
            .and(StoreManLoginLog.Attributes.LOGIN_TIME).lt(date);
        query.addCriteria(criteria);
        
        mongoTemplate.findAndRemove(query, StoreManLoginLog.class);
    }

    @Override
    public List<StoreManLoginLog> queryLoginLogs(String staffId, int startIndex, int limit) {
        Query query = new Query();
        Criteria criteria = new Criteria();
        criteria.and(StoreManLoginLog.Attributes.STAFF_ID).is(staffId);
        query.addCriteria(criteria);
        query.with(new Sort(Direction.DESC, StoreManLoginLog.Attributes.LOGIN_TIME));
        query.skip(startIndex).limit(limit);
        
        return mongoTemplate.find(query, StoreManLoginLog.class);
    }

    @Override
    public int countLoginLogs(String staffId) {
        Query query = new Query();
        Criteria criteria = new Criteria();
        criteria.and(StoreManLoginLog.Attributes.STAFF_ID).is(staffId);
        query.addCriteria(criteria);
        return (int) mongoTemplate.count(query, StoreManLoginLog.class);
    }

}
